package redezeitor;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Mauriverti
 */
public class Server extends Thread {
    int port = 8000;
    
    Roteador router;
    
    public Server (Roteador r) {
        this.router = r;
        this.port = 8000 + r.getRouterId();
    }
    
    @Override
    public void run() {
        try {
            execServer();
        } catch (SocketException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void execServer() throws SocketException, IOException {
        System.out.println("Executando Server");
        
        DatagramSocket serverSocket = new DatagramSocket(port);
        DatagramPacket packet;
        
        byte[] data = new byte[1025];
        
        while (true) {
            packet = new DatagramPacket(data, data.length);
            
            serverSocket.receive(packet);
            
            InetAddress IPCliente = packet.getAddress();
            int port = packet.getPort();
            
            byte[] receivedData = packet.getData();
            String s = new String(receivedData);
            
            s = s.substring(0, s.indexOf(";"));
            
            String vector[] = s.split("\\,");
            
            router.setMatrixNewValues(vector);
            
            System.out.println(s + " / recebido");
        }
    }
    
}
